package cn.bearspark.like.provider.dao.buffer;

import cn.bearspark.framework.redis.starter.buffer.zset.RedisZSetBuffer;
import cn.bearspark.like.provider.dao.key.CommentLikeBufferKeyBuilder;
import cn.bearspark.like.provider.dao.mapper.CommentLikeMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

/**
 * 评论点赞的 ZSet 的缓存器
 *
 * @author f
 */
@Component
public class CommentLikeZSetBuffer extends RedisZSetBuffer {

    private final CommentLikeMapper commentLikeMapper;

    private final CommentLikeBufferKeyBuilder commentLikeBufferKeyBuilder;

    public CommentLikeZSetBuffer(RedisTemplate<String, Object> redisTemplate,
                                 CommentLikeMapper commentLikeMapper,
                                 CommentLikeBufferKeyBuilder commentLikeBufferKeyBuilder) {
        super(redisTemplate);
        this.commentLikeMapper = commentLikeMapper;
        this.commentLikeBufferKeyBuilder = commentLikeBufferKeyBuilder;
    }

    /**
     * 从指定的评论 id List 集合中，过滤出指定用户点赞过的评论 id Set 集合
     *
     * @param commentIdList 指定的评论 id List 集合
     * @param userId        指定的用户 id
     * @return 过滤出的指定用户点赞过的评论 id Set 集合
     */
    public Set<Long> filter(List<Long> commentIdList, long userId) {
        return super.filter(
                commentLikeBufferKeyBuilder.buildUserLikeZSetKey(userId),
                commentIdList,
                missingCommentIdList -> commentLikeMapper.getLikedCommentIdSet(missingCommentIdList, userId)
        );
    }

    /**
     * 清理指定用户点赞指定评论的缓存
     *
     * @param commentId 指定的评论 id
     * @param userId    指定的用户 id
     */
    public void clean(long commentId, long userId) {
        super.clean(commentLikeBufferKeyBuilder.buildUserLikeZSetKey(userId), commentId);
    }
}
